<?php
/*
 * 插件管理
 * author wangjian
 * time 2013-12-01
 *
 */

if (! defined('BASEPATH')) {
	exit('Access Denied');
}
define("__PATH_ROOT__", str_replace("\\","/",FCPATH));
class Index extends MY_Controller {
	private $username ;//当前登录的用户
	private $ip ; //登录的ip地址
	private $table_ ; //表的前缀
	private $admin ;//创始人
	function Index(){
		parent::__construct();
		$this->load->library('admin_common');//加载admin的公用方法
		date_default_timezone_set('Asia/Shanghai');
		$this->load->model('admin/plugin_manager/M_plugin');
		$this->load->model('admin/M_log');
		$this->username = $this->get_login_name(); //得到登录的用户名
		$this->ip = $this->admin_common->get_client_ip();
		$this->table_ = $this->admin_common->table_pre('real_data');
		$this->admin = $this->config->item('web_admin_master');//创始人
	}
	function pluginlist(){
		
		$data_ = $_REQUEST ;
		$action = 'pligin_list' ;
		$action_array = array(
			'pligin_list','ajax_data'
		) ;
		$action = (isset($data_['action']) && in_array($data_['action'], $action_array))?$data_['action']:'pligin_list';
		
		if($action == 'pligin_list'){
			$this->load->view('admin/plugin_manager/views_plugin_list');
		}elseif($action == 'ajax_data'){
			$this->ajax_get_data();
			die();
		}
	}
	//获取系统列表数据，返回json数据
	private function ajax_get_data(){

		$post_data = $this->input->post(NULL,true) ;
		$where = ' where 1=1';
		
		
		if(isset($post_data['plus_name']) && $post_data['plus_name'] != "" ){
			$plus_name = str_replace("'", "''", strip_tags(htmlspecialchars($post_data['plus_name'])));  //插件名称
			$match_array = array(1=>" AND `plugin_name` like '%{$plus_name}%'",2=>" AND `plugin_name` = '{$plus_name}'");
			if(isset($post_data['match']) && array_key_exists($post_data['match'], $match_array)){
				$where.=$match_array[$post_data['match']];
			}
			
		}
		if(isset($post_data['id']) && intval($post_data['id']) != "" && intval($post_data['id']) >0){
			$id = intval($post_data['id']);
			$where.=" AND `id` = '{$id}'";
		}
		if(isset($post_data['status']) && in_array($post_data['status'],array('0','1','2'))){
			
			$where.=" AND `status` = '{$post_data['status']}'";
		}
		
		if(!isset($post_data['page'])){
			$page  =1 ;
		}else{
			$page = intval($post_data['page']);
		}
	
		$sql_count = "SELECT count(*) as tt FROM {$this->table_}common_plugin_manager".$where;
		
		$total = $this->M_plugin->query_count($sql_count);
		
		$per_page = 10;//每一页显示的数量
		$page_string = $this->page_string($total, $per_page, $page);
		$limit = ($page-1)*$per_page;
		$sql = "SELECT * FROM {$this->table_}common_plugin_manager $where  ORDER BY id DESC LIMIT ".$limit.",".$per_page;
		$res = $this->M_plugin->querylist($sql);
		$status_array = array(
			1=>'<font color="green">正常</font>',
			0=>'<font color="blue">失效</font>',
			2=>'<font color="red">删除</font>'
		);
		if($res){
			foreach($res as $res_k=>$res_v){
				$res[$res_k]['status'] = isset($status_array[$res_v['status']])?$status_array[$res_v['status']]:'';
			}
		}
		$data['result'] = $res ;
		$data['page_string'] = $page_string ;	
		
		echo $this->admin_common->result_to_towf_new($data,'','',null);
	}
	function plugin_add(){
		//添加系统
		$data_ = $_REQUEST ;
		$action = 'system_list' ;
		$action_array = array(
			'add','add_do'
		) ;
		$action = (isset($data_['action']) && in_array($data_['action'], $action_array))?$data_['action']:'add';
		if($action == 'add'){
			
			//echo "<pre>";
			//print_r($res_category);
			$this->load->view('admin/plugin_manager/views_plugin_add');
		}elseif($action  == 'add_do'){
			$this->add_do();
		}
		
	}
	private function clear_menu_cache(){
	/*	$path = $this->config->item('cache_path');
    	$cache_path = ($path == '') ? APPPATH.'cache/' : $path;
    	$uri =	$this->config->item('base_url').
				$this->config->item('index_page').
				"admin/index/menu";
				$cache_path .= md5($uri);
			
		if(file_exists(__PATH_ROOT__."/".$cache_path)){
			if(is_really_writable(__PATH_ROOT__."/".$cache_path)){
				@unlink(__PATH_ROOT__."/".$cache_path);
			}
		}*/
		$this->load->library('cache_common');//加载清除缓存文件的方法
		$this->cache_common->clear_menu_cache();
	}
	private function add_do(){
		$post_data = $this->input->post(NULL,true) ;
		$plus_name = html_escape($this->admin_common->do_addslashes(trim(isset($post_data['plus_name'])?$post_data['plus_name']:'')));		
		
		if(iconv_strlen($plus_name,'utf-8') <3 || iconv_strlen($plus_name,'utf-8')>16){
			showmessage('插件长度必须在3-16之间','admin/plus_manager/index/plugin_add',3,0);
			exit();
		}
		
		
	
		$data = array(
			'plugin_name'=>$plus_name,
			
			'addtime'=>date("Y-m-d H:i:s",time()),
			'plugin_addperson'=>$this->username,
			'status'=>(isset($post_data['status']) && in_array($post_data['status'],array('0','1','2')))?$post_data['status']:'0'
		);
		
		$array = $this->M_plugin->insert_one($data,"{$this->table_}common_plugin_manager");
	
		if($array['affect_num'] >=1){
			/* $c_array = array();
			if(isset($post_data['c_name']) && isset($post_data['c_path'])){
				if($post_data['c_name'] != ''){
					for($k = 0 ; $k<count($post_data['c_name']);$k++){
						if(isset($post_data['c_path'][$k]) && $post_data['c_path'][$k]){
							$c_array[] = array(
								'url'=>$post_data['c_path'][$k],
								'c_name'=>$post_data['c_name'][$k],
								'plugin_id'=>$array['insert_id'],
								'isfunction'=>isset($post_data['isfunction'][$k])?$post_data['isfunction'][$k]:0,
							);
						}
					}
				}
			} */
		/* 	if($c_array){
				for($kk = 0 ;$kk<count($c_array);$kk++){
					$this->M_plugin->insert_one($c_array[$kk],"{$this->table_}common_plugin_controller");
				}
			} */
			$this->M_log->insert($array['sql'],'log_plugin_add',$this->username,$this->ip,1,"添加插件{$plus_name}成功"); //插入日志记录
			/*清除左边的菜单缓存*/
			//$this->clear_menu_cache();
			/*清除左边的菜单缓存*/
			
			showmessage("添加插件{$plus_name}成功",'admin/plus_manager/index/pluginlist',3,1);
			exit();
		}else{
			$this->M_log->insert($array['sql'],'log_plugin_add',$this->username,$this->ip,0,"添加插件{$plus_name}成功"); //插入日志记录
			showmessage("添加插件{$plus_name}失败",'admin/plus_manager/index/plugin_add',3,0);
		}
	
	}
	//编辑
	function plugin_edit(){
	
		$data_ = $_REQUEST ;
		$action = 'plugin_edit' ;
		$action_array = array(
			'plugin_edit','plugin_edit_do'
		) ;
		$action = (isset($data_['action']) && in_array($data_['action'], $action_array))?$data_['action']:'plugin_edit';
		if($action == 'plugin_edit'){
		
			$id = (isset($data_['id']) && $data_['id'])?intval($data_['id']):'0';
			$sql_show = "SELECT * FROM `{$this->table_}common_plugin_manager` where id = '{$id}'" ;
			$row = $this->M_plugin->querylist($sql_show);
			$one = array();
			$one = (isset($row[0])&&!empty($row[0]))?$row[0]:'' ;
			if(empty($one)){
				showmessage("参数错误",'admin/plus_manager/index/pluginlist',3,0);
				exit();
				
			}
			
			//$sql_category = "SELECT * FROM `{$this->table_}common_plugin_controller` where reid = 0 and isfunction = 0 and plugin_id = '{$id}' order by reid asc ";
			//$res_category = $this->M_plugin->querylist($sql_category);
			$sql_controller = "SELECT * FROM `{$this->table_}common_plugin_controller` WHERE `plugin_id` = '{$id}' order by reid asc";
			$c_array = $this->M_plugin->querylist($sql_controller);
			$c_array_data = array();
			if($c_array){
				foreach($c_array as $c_key=>$c_val){
					$c_array_data[$c_val['id']] = $c_val;
				}
			}
			
			$this->load->library('plugin_manager_common');
			$c_array_data = $this->plugin_manager_common->format_tree($c_array_data);
			
			$data = array(
				'one'=>$one,
				'c_array'=>$c_array_data,
				//'category'=>$res_category
			);
			
			$this->load->view('admin/plugin_manager/views_plugin_edit',$data);
		}elseif($action  == 'plugin_edit_do'){
			$this->plus_edit_do();
		}
	}
	//编辑处理
	private function plus_edit_do(){
	
		$data_ = $_REQUEST ;
		$id = intval(isset($data_['id'])?$data_['id']:'0');
		$plugin_name = html_escape($this->admin_common->do_addslashes(trim($data_['plugin_name'])));		
		
		$status = (isset($data_['status']) && in_array($data_['status'],array('1',"2","0")))?$data_['status']:'0';
		if(iconv_strlen($plugin_name,'utf-8') <3 || iconv_strlen($plugin_name,'utf-8')>16){
			showmessage('插件名称长度必须在3-16之间','admin/plus_manager/index/plugin_edit?id='.$id,3,0);
			exit();
		}
		$c_array = array();
		$c_array_insert = array();
		$array_top_insert = array();
	/*	echo "<pre>";
		print_r($data_) ;die();*/
		if(isset($data_['c_name']) && isset($data_['c_path'])){
			if($data_['c_name'] != '' && $data_['c_path'] != "" ){
				for($k = 0 ; $k<count($data_['c_name']);$k++){
					if(isset($data_['c_path'][$k]) && $data_['c_path'][$k]){
						
						if(isset($data_['ids'][$k]) && intval($data_['ids'][$k]) > 0 ){
							//有id 说明是数据库中本身有的数据，更新数据
							/*$c_array[] = array(
									'url'=>isset($data_['c_path'][$k])?$data_['c_path'][$k]:'',
									'c_name'=>isset($data_['c_name'][$k])?$data_['c_name'][$k]:'',
									'plugin_id'=>$id,
									'isfunction'=>isset($data_['isfunction'][$k])?$data_['isfunction'][$k]:0,
									'reid'=>0,
									
							);*/
							$c_name = isset($data_['c_name'][$k])?$data_['c_name'][$k]:'' ;
							$url = isset($data_['c_path'][$k])?$data_['c_path'][$k]:'' ;
							$myid = intval($data_['ids'][$k] );
							$this->M_plugin->update_data("UPDATE `{$this->table_}common_plugin_controller` SET `c_name` = '{$c_name}',`url` = '{$url}' where id = '{$myid}' ");//更新控制器插件
						}else{
							$array_top_insert[] = array(
									'url'=>isset($data_['c_path'][$k])?$data_['c_path'][$k]:'',
									'c_name'=>isset($data_['c_name'][$k])?$data_['c_name'][$k]:'',
									'plugin_id'=>$id,
									'isfunction'=>isset($data_['isfunction'][$k])?$data_['isfunction'][$k]:0,
									'reid'=>0,
									
							);	
						
						}	
							
					}
				}
			}
		}
		
	////////////////////////////////////////////////////子类///////////////
	if(isset($data_['c_child_name']) && isset($data_['c_child_path']) && isset($data_['reid'])){
			if($data_['c_child_name'] != '' && $data_['c_child_path'] && $data_['reid']){
				for($kk = 0 ; $kk<count($data_['c_child_name']);$kk++){
							if(isset($data_['sonid'][$kk]) && intval($data_['sonid'][$kk]) > 0){
								//更新数据
								$c_name = isset($data_['c_child_name'][$kk])?$data_['c_child_name'][$kk]:'' ;
								$url = isset($data_['c_child_path'][$kk])?$data_['c_child_path'][$kk]:'' ;
								$myid = intval($data_['sonid'][$kk]);
								$this->M_plugin->update_data("UPDATE `{$this->table_}common_plugin_controller` SET `c_name` = '{$c_name}',`url` = '{$url}' where id = '{$myid}' ");//更新控制器插件
							}else{
								$c_array_insert[] = array(
									'url'=>$data_['c_child_path'][$kk],
									'c_name'=>$data_['c_child_name'][$kk],
									'plugin_id'=>$id,
									'isfunction'=>1,
									'reid'=>isset($data_['reid'][$kk])?$data_['reid'][$kk]:0,
									
								);						
							}							
				}
			}
		}
		
		$sql_update = "UPDATE `{$this->table_}common_plugin_manager` set plugin_name = '{$plugin_name}',status = '{$status}'" ;
	
		$sql_update.=" WHERE id = '{$id}'";
	
		$num = $this->M_plugin->update_data($sql_update);//更新插件
		//先删除插件		
		//$this->M_plugin->del_data("DELETE FROM `{$this->table_}common_plugin_controller` WHERE `plugin_id` = '{$id}'");//删除插件
		
		if($array_top_insert){//插入插件				
			for($kk_ = 0 ;$kk_<count($array_top_insert);$kk_++){
				$this->M_plugin->insert_one($array_top_insert[$kk_],"{$this->table_}common_plugin_controller");
			}
		}
		if($c_array_insert){//插入插件				
			for($kk_insert = 0 ;$kk_insert<count($c_array_insert);$kk_insert++){
				$this->M_plugin->insert_one($c_array_insert[$kk_insert],"{$this->table_}common_plugin_controller");
			}
		}		
		/*清除左边的菜单缓存*/
		//$this->clear_menu_cache();
		/*清除左边的菜单缓存*/
		$this->M_log->insert($sql_update,'log_plugin_edit',$this->username,$this->ip,1,"删除修改成功"); //插入日志记录
		showmessage('修改成功','admin/plus_manager/index/plugin_edit?id='.$id,3,1);
		
		
	}
	//删除
	function plus_del(){
		
		$post_data = $_REQUEST;
		$id = ($post_data['id']);
		$in_id = '' ;
		if($id){
			$ids = explode(",", $id);
			for($k = 0 ;$k<count($ids);$k++){
				$in_id.=intval($ids[$k]).",";
			}
		}
		$in_id = rtrim($in_id,",") ;
		if(empty($in_id)){
			echo $this->admin_common->result_to_towf_new('',0,'参数传递出错',null);
			die();
		}
		
		$sql="update  `{$this->table_}common_plugin_manager` SET `status` = '2' WHERE id in ($in_id)";
		$num = $this->M_plugin->update_data($sql);
		$code = 0 ;
		$message = '' ;
		if($num>=1){
			$code = 1 ;
			$message = '删除成功';
			$this->M_log->insert($sql,'log_plugin_del',$this->username,$this->ip,1,"删除插件成功"); //插入日志记录
		}else{
			$code = 0 ;
			$message= '服务器繁忙，或者地址出错' ;
			$this->M_log->insert($sql,'log_plugin_del',$this->username,$this->ip,0,"删除插件失败"); //插入日志记录
		}
		/*清除左边的菜单缓存*/
		$this->clear_menu_cache();
		/*清除左边的菜单缓存*/
		echo $this->admin_common->result_to_towf_new('',$code,$message,null);
		return ;
	}

	/*@function page_string
	 *@分页返回数据
	 *@total 总的数量
	 *@page_num 每一页显示的数量
	 *@page 当前是第几页数据
	 */
	private function page_string($total,$page_num,$page){
		$page_string = '' ;
		$this->load->library('pagination');//加载分页类
		$this->load->library('MY_Pagination');//加载分页类
		$config['total_rows'] = $total;
		$config['use_page_numbers'] =true; // 当前页结束样式
		$config['per_page'] = $page_num; // 每页显示数量，为了能有更好的显示效果，我将该数值设置得较小
		$config['full_tag_open'] = '<div class="pg">'; // 分页开始样式
		$config['full_tag_close'] = '</div>'; // 分页结束样式
		$config['first_link'] = '首页'; // 第一页显示
		$config['last_link'] = '末页'; // 最后一页显示
		$config['next_link'] = '下一页 >'; // 下一页显示
		$config['prev_link'] = '< 上一页'; // 上一页显示
		$config['cur_tag_open'] = ' <a class="current">'; // 当前页开始样式
		$config['cur_tag_close'] = '</a>'; // 当前页结束样式
		$config['uri_segment'] = 6;
		$config['anchor_class']='class="ajax_page" ';
		$this->pagination->cur_page = $page ;
		$this->pagination->initialize($config); // 配置分页
		$page_string =  $this->pagination->create_links(true,'ajax_data');
		return $page_string ;
	}
	
}
